package forms;

import helpers.CrawlerHelper;
import helpers.StringHelper;
import helpers.TranslateHelper;
import helpers.ValidateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import models.ArticleModel;
import entities.Article;

public class ArticleForm {
	public static TreeMap<String, Object> checkValid(HttpServletRequest request, Article article) {
		TreeMap<String, Object> form = new TreeMap<String, Object>();
		TreeMap<String, String> checkValid = new TreeMap<String, String>();
		
		String title = (String) request.getParameter("title");
		String content = (String) request.getParameter("content");
		String name = (String) request.getParameter("name");
		String email = (String) request.getParameter("email");
		String website = (String) request.getParameter("website");
		String keywords = (String) request.getParameter("keywords");
		
		
		if (article.getCreator().isEmpty()) {
			if (name == null || name.isEmpty()) {
				checkValid.put("name", "Please input author name.");
				article.setAuthorName("");
			} else {
				article.setAuthorName(name);
			}
			
			if (email == null || email.isEmpty()) {
				checkValid.put("email", "Please input author email.");
				article.setEmail("");
			} else if (!ValidateHelper.isEmail(email)) {
				checkValid.put("email", "Author email is not valid");
				article.setEmail(email);
			} else {	
				article.setEmail(email);
			}
			
			if (website != null) {
				article.setWebsite(website);
			}
		}
		
		if (title == null || title.isEmpty()) {
			checkValid.put("title", "Title is not empty.");
			article.setTitle("");
		} else {
			article.setTitle(title);
		}
		
		if (content == null || content.isEmpty()) {
			checkValid.put("content", "Content is not empty.");
			article.setContent("");
		} else {
			Document doc = Jsoup.parse(content);
			Elements elms = doc.select("a");
			if (elms.size() > 5) {
				checkValid.put("content", "Maximum link: 5");
			}
			article.setContent(content);
		}
		
		if (keywords != null && !keywords.isEmpty()) {
			String[] k = keywords.split(",");
			List<String> keys = new ArrayList<String>();
			for (int i = 0; i < k.length; i++) {
				keys.add(k[i].trim());
			}
			
			if (k.length > 5) {
				checkValid.put("keywords", "Maximum: 5 keywords");
			}
			
			
			article.setKeywords(keys);
			article.setTags(keywords);
		}
		
		
		form.put("checkValid", checkValid);
		form.put("article", article);
		
		return form;
	}
}
